package com.cnpinxi.service;

import com.alibaba.fastjson.JSONObject;
import com.cnpinxi.domain.weChat.UserWechatInfo;
import com.cnpinxi.log.LogFactory;
import com.cnpinxi.service.*;
import com.cnpinxi.tool.HttpClientHelper;
import com.cnpinxi.tool.json.JsonHandler;
import com.cnpinxi.util.FixedData;
import com.cnpinxi.util.WeiXinUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Created by Baggio on 2017-3-20.
 */
@Service("weChatService")
public class WeChatServiceImpl implements com.cnpinxi.service.WeChatService {
    protected Logger logger = LogFactory.getLogger(getClass());
/*    @Autowired
    JsapiTicketMapper jsapiTicketMapper;
    @Autowired
    RedisCache redisCache;*/

    @Override
    public String getAccessToken() {

        String  accessTokenKey = "accessTokenKey_"+ FixedData.ENTERPRISE_APP_ID;
        String  accessToken = null;
        try {
           /* accessToken =(String) redisCache.get(accessTokenKey);*/
            if (StringUtils.isBlank(accessToken)){
                logger.info("accessToken is null in redies 重新获取accessToken======>>>");
                String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + FixedData.ENTERPRISE_APP_ID + "&secret=" + FixedData.APP_APPSECRET;
                String dsd = HttpClientHelper.doGet(url);
                logger.info("accessToken====>>>"+dsd);
                JSONObject jon=JSONObject.parseObject(dsd);

                  accessToken=(String)jon.get("access_token");
                  if(StringUtils.isBlank(accessToken)){
                      throw new RuntimeException("获取accessToken失败！accessToken is null");
                  }
                logger.info("accessToken==is=???>>"+accessToken);
            /*    redisCache.put(accessTokenKey,accessToken,EXPIRE);*/
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("获取accessToken失败=======》》》》》");
        }

        logger.info("accessToken======>>>"+accessToken);
        return accessToken;
    }

    @Override
    public String getTicket() {
        //String  ticketKey = "ticketKey_"+FixedData.ENTERPRISE_APP_ID;
        String  ticket = WeiXinUtils.jsTicket.get("ticket");
        String  timestamp = WeiXinUtils.jsTicket.get("timestamp");
        Long nowTimestamp=new Date().getTime();
        Long subTimestamp=null;
        try {
            try {
                if( StringUtils.isNotBlank(timestamp)){
                    Long   ticketTimestamp=Long.parseLong(timestamp);
                    if(ticketTimestamp!=null){
                        subTimestamp=  nowTimestamp-ticketTimestamp;
                        logger.info("subTimestamp===>>"+subTimestamp);
                    }

                }
            } catch (NumberFormatException e) {
                logger.info("timestamp 转换出错==》》"+timestamp);
                e.printStackTrace();
            }


          /*  ticket =(String) redisCache.get(ticketKey);*/
            if (StringUtils.isBlank(ticket) || (StringUtils.isNotBlank(ticket) && StringUtils.isBlank(timestamp))
                    ||  (StringUtils.isNotBlank(ticket) &&   subTimestamp!=null && subTimestamp> WeiXinUtils.EXPIREIN)
                    ){
                logger.info("ticket is null in redies 重新获取ticket======>>>"+ticket+"["+timestamp+"]");
                String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+getAccessToken()+"&type=jsapi";
                String dsd = HttpClientHelper.doGet(url);
                logger.info("dsd====>>>"+dsd);
                JSONObject jon=JSONObject.parseObject(dsd);

                ticket=(String)jon.get("ticket");
                if(StringUtils.isBlank(ticket)){
                    throw new RuntimeException("获取ticket失败！ticket is null");
                }
                logger.info("ticket==is=???>>"+ticket);
                WeiXinUtils.jsTicket.put("ticket",ticket);
                WeiXinUtils.jsTicket.put("timestamp",String.valueOf(nowTimestamp));
               /* redisCache.put(ticketKey,ticket,EXPIRE);*/
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("获取ticket失败=======》》》》》"+e.getMessage());


        }

        logger.info("ticket======>>>"+ticket);
        return ticket;
    }



    @Override
    public String getopenId(String appId, String code) {
        String url= "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+ FixedData.ENTERPRISE_APP_ID+"&secret="+FixedData.APP_APPSECRET+"&code="+code+"&grant_type=authorization_code";
      String openid="";
        try {
            String dsd=   HttpClientHelper.doGet(url);
            JSONObject jon=JSONObject.parseObject(dsd);
            logger.info("jon==>"+jon.toString());
            openid=(String)jon.get("openid");
        } catch (Exception e) {
            e.printStackTrace();
        }


        return openid;
    }
    @Override
    public UserWechatInfo getUserWechatInfo(String accessToken, String openId) {
        String url= "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+accessToken+"&openid="+openId;
        UserWechatInfo userWechatInfo=new UserWechatInfo();
        try {
            String getUserWechatInfoJson=   HttpClientHelper.doGet(url);
            logger.info("getUserWechatInfoJson==>"+getUserWechatInfoJson);
            getUserWechatInfoJson = new String(getUserWechatInfoJson.getBytes("ISO-8859-1"), "UTF-8");

            userWechatInfo=  (UserWechatInfo) JsonHandler.jsonToObject(getUserWechatInfoJson,UserWechatInfo.class);
            logger.info(userWechatInfo.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return userWechatInfo;
    }

}
